package tuding.android.bigplanettracks.tracks.db;

import java.util.ArrayList;
import java.util.List;

import tuding.android.bigplanettracks.BigPlanet;
import tuding.android.bigplanettracks.maps.Marker;
import tuding.android.bigplanettracks.maps.MarkerManager;
import tuding.android.bigplanettracks.maps.storage.SQLLocalStorage;
import tuding.android.bigplanettracks.maps.tuding.ActionNotes;
import tuding.android.bigplanettracks.tracks.MyTimeUtils;
import tuding.android.bigplanettracks.tracks.TrackAnalyzer;
//import tuding.android.bigplanettracks.StatsActivity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

/**
 * @author TYTung, taiyuchen
 * @version 0.1
 */
public class TrackDBAdapter {
	
	/**
	 * TRACKS_TABLE
	 */
	protected final static String TRACKS_TABLE = "tracks";
	protected final static String TUDING_TABLE = "tuding";
	public final static String FIELD_trackid = "trackid"; // column 0 PK
	public final static String FIELD_name = "name"; // column 1
	public final static String FIELD_description = "description";// column 2
	public final static String FIELD_startTime = "start_time"; // column 3
	public final static String FIELD_totalTime = "total_time"; // column 4
	public final static String FIELD_totalDistance = "total_distance"; // column 5
	public final static String FIELD_averageSpeed = "average_speed"; // column 6
	public final static String FIELD_maximumSpeed = "maximum_speed"; // column 7
	public final static String FIELD_minAltitude = "min_altitude"; // column 8
	public final static String FIELD_maxAltitude = "max_altitude"; // column 9
	public final static String FIELD_trackPoints = "points"; // column 10
	public final static String FIELD_trackSource = "source"; // column 11
	public final static String FIELD_measureVersion = "measure_version"; // column 12
	public final static String FIELD_action_note = "notes"; // column 13
	public final static String FIELD_action_photo = "photo"; // column 14
	public final static String FIELD_uploaded = "uploaded_flag"; // column 15
	
	public final static String FIELD_td_tid = "tuding_tid"; // column 1
	public final static String FIELD_c2 = "tuding_c2"; // column 2
	public final static String FIELD_c3 = "tuding_c3"; // column 3
	public final static String FIELD_c4 = "tuding_c4"; // column 4
	public final static String FIELD_c5 = "tuding_c5"; // column 5
	public final static String FIELD_privacy = "tuding_c6"; // column 6
	// more
	
	
	
	/**
	 * WAYPOINTS_TABLE
	 */
	private final static String WAYPOINTS_TABLE = "waypoints";
	public final static String FIELD_pointid = "pointid"; // column 0 PK
//	public final static String FIELD_trackid = "trackid"; // column 1 FK
	public final static String FIELD_time = "time";// column 2
	public final static String FIELD_latitude = "latitude";// column 3
	public final static String FIELD_longitude = "longitude";// column 4
	public final static String FIELD_altitude = "altitude";// column 5
	public final static String FIELD_speed = "speed";// column 6
	public final static String FIELD_bearing = "bearing";// column 7
	public final static String FIELD_accuracy = "accuracy";// column 8
	public final static String FIELD_actionType = "action_type"; 
	public final static String FIELD_actionID = "action_id";
	
	private final static String GMTTime = "GMTTime";
	
	private final static String DATABASE_NAME = "tracks.db";
	
	protected static final String TRACKS_TABLE_TUDING ="CREATE TABLE IF NOT EXISTS " + TUDING_TABLE + " (" 
			+ FIELD_trackid + " INTEGER primary key, " 
			+ " "+ FIELD_c2     + " INTEGER DEFAULT '0', "
			+ " "+ FIELD_c3     + " INTEGER DEFAULT '0', "
			+ " "+ FIELD_c4     + " INTEGER DEFAULT '0', "
			+ " "+ FIELD_c5     + " INTEGER DEFAULT '0', "
			+ " "+ FIELD_privacy+ " SHORT   DEFAULT '0', "
			+ " "+ FIELD_td_tid + " LONG    DEFAULT '0');";
	
	protected static final String TRACKS_TABLE_DDL ="CREATE TABLE IF NOT EXISTS " + TRACKS_TABLE + " (" 
	+ FIELD_trackid + " INTEGER primary key autoincrement, " 
	+ " "+ FIELD_name + " VARCHAR,"
	+ " "+ FIELD_description + " VARCHAR, "
	+ " "+ FIELD_startTime + " CHAR(20), "
	+ " "+ FIELD_totalTime + " LONG, "
	+ " "+ FIELD_totalDistance + " FLOAT, "
	+ " "+ FIELD_averageSpeed + " FLOAT, "
	+ " "+ FIELD_maximumSpeed + " FLOAT, "
	+ " "+ FIELD_minAltitude + " DOUBLE, "
	+ " "+ FIELD_maxAltitude + " DOUBLE, "
	+ " "+ FIELD_trackPoints + " INTEGER, "
	+ " "+ FIELD_trackSource + " CHAR(4), "
	+ " "+ FIELD_action_note + " INTEGER DEFAULT '0', "
	+ " "+ FIELD_action_photo + " INTEGER DEFAULT '0', "
	+ " "+ FIELD_uploaded + " SHORT DEFAULT '0', "
	
	+ " "+ FIELD_measureVersion + " INTEGER);";

	private static final String TRACK_POINTS_TABLE_DDL ="CREATE TABLE IF NOT EXISTS " + WAYPOINTS_TABLE + " (" 
	+ FIELD_pointid + " INTEGER primary key autoincrement, " 
	+ " "+ FIELD_trackid + " INTEGER NOT NULL,"
	+ " "+ FIELD_time + " CHAR(20), "
	+ " "+ FIELD_latitude + " DOUBLE DEFAULT '0', "
	+ " "+ FIELD_longitude + " DOUBLE DEFAULT '0', "
	+ " "+ FIELD_altitude + " DOUBLE DEFAULT '0', "
	+ " "+ FIELD_speed + " FLOAT DEFAULT '0', "
	+ " "+ FIELD_bearing + " FLOAT DEFAULT '0', "
	+ " "+ FIELD_accuracy + " FLOAT DEFAULT '0', "
	+ " "+ FIELD_actionType + " INTEGER DEFAULT '0',"
	+ " "+ FIELD_actionID + " LONG DEFAULT '0');";

	private SQLiteDatabase db;
	
	//---opens the database---
	public TrackDBAdapter open() throws SQLException {
		if (db == null) {
			String sqliteFilePath = SQLLocalStorage.TRACK_PATH + DATABASE_NAME;
			db = SQLiteDatabase.openDatabase(sqliteFilePath, null,
					SQLiteDatabase.CREATE_IF_NECESSARY);
			
//			System.out.println("db.getVersion() = "+db.getVersion());
			if (db.getVersion() < 1) {
				db.beginTransaction();
				try {
					// has database of BPT 2.0 and update to BPT 2.1
					db.execSQL(SQLConstants.SQL_UPDATE_1_1);
					db.execSQL(SQLConstants.SQL_UPDATE_1_2);
					db.execSQL(SQLConstants.SQL_UPDATE_1_3);
					db.execSQL(TRACKS_TABLE_DDL);
					db.execSQL(SQLConstants.SQL_UPDATE_1_5);
					db.execSQL(SQLConstants.SQL_UPDATE_1_6);
					db.execSQL(SQLConstants.SQL_UPDATE_1_7);
					db.setTransactionSuccessful();
				} catch (SQLiteException e) {
					// no database of BPT 2.0 (i.e. new installation)
					db.execSQL(TRACKS_TABLE_DDL);
					db.execSQL(TRACK_POINTS_TABLE_DDL);
					db.execSQL(TRACKS_TABLE_TUDING);
					db.setTransactionSuccessful();
				} finally {
					db.endTransaction();
					db.setVersion(1);
					//System.out.println("Database has upgraded to version "+db.getVersion());
				}
			} else {
				db.execSQL(TRACKS_TABLE_DDL);
				db.execSQL(TRACK_POINTS_TABLE_DDL);
				db.execSQL(TRACKS_TABLE_TUDING);
			}
		}
		return this;
	}
	
	//---closes the database---	
	public void close() {
		if (db != null) {
			db.close();
			db = null;
		}
	}
	
	

	public long insertNewTrack(String trackName, String trackDescription, String startGMTTime, String trackSource) {
		long trackID = 0;
		db.beginTransaction();
		try {
			ContentValues cv = new ContentValues();
			cv.put(FIELD_name, trackName);
			cv.put(FIELD_description, trackDescription);
			cv.put(FIELD_startTime, startGMTTime);
			cv.put(FIELD_trackSource, trackSource);
			cv.put(FIELD_uploaded, 0);
			trackID = db.insert(TRACKS_TABLE, null, cv);
			db.setTransactionSuccessful();
		} catch (Exception e) {
		} finally {
		    db.endTransaction();
		}
		return trackID;
	}
	
	// add one marker with actions: 
	public long insertNewActionMarker(long trackID, Marker ActionMarker){
		if(trackID != 0) {
			db.beginTransaction();
			try {
				ContentValues cv = new ContentValues();
				Location loc = ActionMarker.place.getLocation();
				if(loc==null || loc.getLatitude()==0 || loc.getLongitude()==0) {
					return 0;
				}
				String strGMTTime = "";
				strGMTTime = MyTimeUtils.getGMTTimeString(loc.getTime());
				cv = new ContentValues();
				cv.put(FIELD_trackid, trackID);
				cv.put(FIELD_time, strGMTTime);
				cv.put(FIELD_latitude, loc.getLatitude());
				cv.put(FIELD_longitude, loc.getLongitude());
				cv.put(FIELD_altitude, loc.getAltitude());
				cv.put(FIELD_speed, loc.getSpeed());
				cv.put(FIELD_bearing, loc.getBearing());
				cv.put(FIELD_accuracy, loc.getAccuracy());
				cv.put(FIELD_actionType, ActionMarker.actionType);
				cv.put(FIELD_actionID, ActionMarker.actionID);
				db.insert(WAYPOINTS_TABLE, null, cv);
				db.setTransactionSuccessful();
				// update marker number
				// it doesnot work
				// db.rawQuery("update "+TRACKS_TABLE+ " set "+FIELD_action_note+"="+FIELD_action_note+"+1"+" where "+FIELD_trackid+"="+trackID, null); //FIXME
			
				
			} catch (Exception e) {
			   e.printStackTrace();
			} finally {
			    db.endTransaction();
			}
		}
		return trackID;
	}
	
	// add markers' list with actions
	public long insertNewActionMarkerList(long trackID, List<Marker> ActionMarkers){
		if(trackID != 0) {
			db.beginTransaction();
			try {
				ContentValues cv = new ContentValues();
				for (Marker marker: ActionMarkers) {
					Location loc = marker.place.getLocation();
					if(loc==null || loc.getLatitude()==0 || loc.getLongitude()==0) {
						Log.e("MARKER","Find a null point, it should be remove early in MM addMarker() function! "+loc.getLatitude()+" "+loc.getLongitude());
						continue;
					}
					String strGMTTime = "";
					strGMTTime = MyTimeUtils.getGMTTimeString(loc.getTime());
					cv = new ContentValues();
					cv.put(FIELD_trackid, trackID);
					cv.put(FIELD_time, strGMTTime);
					cv.put(FIELD_latitude, loc.getLatitude());
					cv.put(FIELD_longitude, loc.getLongitude());
					cv.put(FIELD_altitude, loc.getAltitude());
					cv.put(FIELD_speed, loc.getSpeed());
					cv.put(FIELD_bearing, loc.getBearing());
					cv.put(FIELD_accuracy, loc.getAccuracy());
					if(marker.actionType != 0) {
						Log.i("MARKER", "an action Marker is stored");
					    cv.put(FIELD_actionType, marker.actionType);
					    cv.put(FIELD_actionID, marker.actionID);
					}
					db.insert(WAYPOINTS_TABLE, null, cv);
				}
				db.setTransactionSuccessful();
				
			} catch (Exception e) {
			   e.printStackTrace();
			} finally {
			    db.endTransaction();
			} 
		}
		return trackID;
	}
	
	public void removeActionMarker(int actionType, long actionID) {
		db.beginTransaction();
		int rc = 0;
		//int trackID = 0;
		int pointID = 0;
		Cursor mCursor = null;
		//Cursor mCursor_tmp = null;
		
		try {
			//mCursor = db.rawQuery("select "+FIELD_pointid+", "+FIELD_trackid+" from "+WAYPOINTS_TABLE+" where "+FIELD_actionType + "=" + actionType+" and "+FIELD_actionID+"="+actionID, null);
			mCursor = db.query(true, WAYPOINTS_TABLE, new String[] {
					FIELD_pointid,
					FIELD_trackid
					},
					FIELD_actionType + "=" + actionType+" and "+FIELD_actionID+"="+actionID, 
		            null,
					null, 
					null, 
					null, 
					null );
			if(mCursor != null) mCursor.moveToFirst();
			pointID = mCursor.getInt(0);
			//trackID = mCursor.getInt(1);
			
			
		    //rc = db.delete(WAYPOINTS_TABLE, FIELD_actionType + "=" + actionType+" and "+FIELD_actionID+"="+actionID, null);
		    rc = db.delete(WAYPOINTS_TABLE, FIELD_pointid + "=" + pointID, null);
		    db.setTransactionSuccessful();
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			db.endTransaction();
			if(mCursor!=null)mCursor.close();
			Log.i("TAP", "removeActionMarker num "+rc+" "+FIELD_actionType + "=" + actionType+" and "+FIELD_actionID+"="+actionID);
		}
		
		
		
		/* update notes and photo num */
		/* very ugly routine
		try {
			mCursor_tmp = db.rawQuery("select "+FIELD_action_note+", "+FIELD_action_photo+" from "+TRACKS_TABLE+" where "+FIELD_trackid+"="+BigPlanet.currentTrackID, null);
			//mCursor_tmp = db.rawQuery("select * from "+TRACKS_TABLE+" where "+FIELD_trackid+"="+BigPlanet.currentTrackID, null);
			Log.d("DEL", "select "+FIELD_trackid+","+FIELD_action_note+","+FIELD_action_photo+" from "+TRACKS_TABLE+" where "+FIELD_trackid+"="+BigPlanet.currentTrackID);

			if(mCursor_tmp != null) {
				mCursor_tmp.moveToFirst();
				Log.w("DEL", "find the line!");
				int notenum = mCursor_tmp.getInt(0);
				int photonum = mCursor_tmp.getInt(1);
				
				Log.d("DEL", "actionType is "+actionType);

				if(actionType == MarkerManager.ACTION_TYPE_NOTES) {
					Log.d("DEL", "actionType is notes");
					db.rawQuery("update "+TRACKS_TABLE+ " set "+FIELD_action_note+"="+(notenum-1)+" where "+FIELD_trackid+"="+BigPlanet.currentTrackID, null);
				}
				if(actionType == MarkerManager.ACTION_PHOTO_MARKER) {
					Log.d("DEL", "actionType is notes");
					db.rawQuery("update "+TRACKS_TABLE+ " set "+FIELD_action_photo+"="+(photonum-1)+" where "+FIELD_trackid+"="+BigPlanet.currentTrackID, null);
				}
			} else {
				Log.w("DEL", "didnot find the line!");
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			if(mCursor_tmp!=null)mCursor_tmp.close();
			//db.endTransaction();
		} */
		// get notes and photo num directly from actionNotes table
		
		try {
			if(BigPlanet.currentTrackID != 0) {
				db.beginTransaction();
				ActionNotes aN = new ActionNotes();
				int actionNotesNum = aN.getActionNotesNumByTrackID((int)BigPlanet.currentTrackID);
				int actionPhotoNum = aN.getActionPhotoNumByTrackID((int)BigPlanet.currentTrackID);
				aN.close();
				Log.d("DEL", "tid is "+BigPlanet.currentTrackID);
				if(actionType == MarkerManager.ACTION_TYPE_NOTES) {
					ContentValues cv = new ContentValues();
					cv.put(FIELD_trackid, BigPlanet.currentTrackID);
					cv.put(FIELD_action_note, actionNotesNum);
					db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + BigPlanet.currentTrackID, null);
					Log.d("DEL", "actionType is notes: "+actionNotesNum);
				}
				if(actionType == MarkerManager.ACTION_TYPE_PHOTO) {
					ContentValues cv = new ContentValues();
					cv.put(FIELD_trackid, BigPlanet.currentTrackID);
					cv.put(FIELD_action_photo, actionPhotoNum);
					db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + BigPlanet.currentTrackID, null);
				}
				db.setTransactionSuccessful();
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally{
			db.endTransaction();
		}
		
		
	}

	public long insertNewMarker(long trackID, ArrayList<Location> locationList) {
		if(trackID != 0) {
			db.beginTransaction();
			try {
				ContentValues cv = new ContentValues();
				for (Location loc: locationList) {
					if(loc==null || loc.getLatitude()==0 || loc.getLongitude()==0) {
						Log.e("TRACK","Find a null point, it should be remove early in MM addMarker() function! "+loc.getLatitude()+" "+loc.getLongitude());
						continue;
					}
					String strGMTTime = "";
					strGMTTime = MyTimeUtils.getGMTTimeString(loc.getTime());
					//Log.i("TRACK","last strGMTTime: "+strGMTTime);
					cv = new ContentValues();
					cv.put(FIELD_trackid, trackID);
					cv.put(FIELD_time, strGMTTime);
					cv.put(FIELD_latitude, loc.getLatitude());
					cv.put(FIELD_longitude, loc.getLongitude());
					cv.put(FIELD_altitude, loc.getAltitude());
					cv.put(FIELD_speed, loc.getSpeed());
					cv.put(FIELD_bearing, loc.getBearing());
					cv.put(FIELD_accuracy, loc.getAccuracy());
					db.insert(WAYPOINTS_TABLE, null, cv);
				}
				db.setTransactionSuccessful();
			} catch (Exception e) {
			} finally {	
			    db.endTransaction();
			} 
		}
		return trackID;
	}
	
	public long insertTrack(String trackName, String trackDescription, String startGMTTime, 
			ArrayList<Location> locationList, String trackSource) {
		long trackID = 0;
		db.beginTransaction();
		try {
			ContentValues cv = new ContentValues();
			cv.put(FIELD_name, trackName);
			cv.put(FIELD_description, trackDescription);
			cv.put(FIELD_startTime, startGMTTime);
			cv.put(FIELD_trackSource, trackSource);
			cv.put(FIELD_uploaded, 0);
			trackID = db.insert(TRACKS_TABLE, null, cv);
			
			for (Location loc: locationList) {
				String strGMTTime = "";
				strGMTTime = MyTimeUtils.getGMTTimeString(loc.getTime());
				cv = new ContentValues();
				cv.put(FIELD_trackid, trackID);
				cv.put(FIELD_time, strGMTTime);
				cv.put(FIELD_latitude, loc.getLatitude());
				cv.put(FIELD_longitude, loc.getLongitude());
				cv.put(FIELD_altitude, loc.getAltitude());
				cv.put(FIELD_speed, loc.getSpeed());
				cv.put(FIELD_bearing, loc.getBearing());
				cv.put(FIELD_accuracy, loc.getAccuracy());
				db.insert(WAYPOINTS_TABLE, null, cv);
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		return trackID;
	}
	
	//---deletes a particular track---
	public boolean deleteTrack(long rowId) {
		int rowsAffected = 0;
		db.beginTransaction();
		try {
			rowsAffected = db.delete(WAYPOINTS_TABLE, FIELD_trackid + "=" + rowId, null);
			rowsAffected = db.delete(TRACKS_TABLE, FIELD_trackid + "=" + rowId, null);
			ActionNotes aN = new ActionNotes();
			aN.removeActionNotesByTrackID(rowId);
			aN.removeActionPhotoByTrackID(rowId);
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		return rowsAffected > 0;
	}
	
	//---retrieves all the tracks---
	public Cursor getAllTracks() {
		return db.query(TRACKS_TABLE, new String[] {
				FIELD_trackid, 
				FIELD_name,
				FIELD_description,
				FIELD_startTime,
				FIELD_totalTime,
				FIELD_totalDistance,
				FIELD_averageSpeed,
				FIELD_maximumSpeed,
				FIELD_minAltitude,
				FIELD_maxAltitude,
				FIELD_trackPoints,
				FIELD_trackSource,
				FIELD_action_note,
				FIELD_action_photo,
				FIELD_uploaded,
				FIELD_measureVersion }, 
				null, 
				null, 
				null, 
				null, 
				FIELD_trackid + " DESC");
	}
	
	public boolean checkIfDBHasTracks() {
		boolean result = false;
		Cursor mCursor = db.rawQuery("select count("+FIELD_trackid+")"+" from "+TRACKS_TABLE, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
			result = mCursor.getFloat(0) > 0;
			mCursor.close();
		}
		return result;
	}
	
	public long getLatestTrackID()  throws SQLException {
		Cursor mCursor = db.query(true, TRACKS_TABLE, new String[] {
				FIELD_trackid
				}, 
				null, 
				null,
				null, 
				null, 
				FIELD_startTime+" DESC", 
				"1");
		long trackID = 0;
		if (mCursor != null) {
			try {
				mCursor.moveToFirst();
				trackID = mCursor.getLong(0);
			}catch (Exception e) {
				trackID = 0;
			}
		} 
		mCursor.close();
		return trackID;
	}
		
	//---retrieves a particular track---
	public Cursor getTrack(long rowId) throws SQLException {
		Cursor mCursor = db.query(true, TRACKS_TABLE, new String[] {
						FIELD_trackid, 
						FIELD_name,
						FIELD_description,
						FIELD_startTime,
						FIELD_totalTime,
						FIELD_totalDistance,
						FIELD_averageSpeed,
						FIELD_maximumSpeed,
						FIELD_minAltitude,
						FIELD_maxAltitude,
						FIELD_trackPoints,
						FIELD_trackSource,
						FIELD_action_note,
						FIELD_action_photo,
						FIELD_uploaded,
						FIELD_measureVersion
						}, 
						FIELD_trackid + "=" + rowId, 
						null,
						null, 
						null, 
						null, 
						null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public boolean markTrackLoaded(long trackID, boolean uploaded) {
		ContentValues cv = new ContentValues();
		cv.put(FIELD_trackid, trackID);
		cv.put(FIELD_uploaded, uploaded);
		return db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + trackID, null) > 0;
	}
	
	
	//---updates a track---
	public boolean updateTrack(long trackID, String trackName, String trackDescription) {
		ContentValues cv = new ContentValues();
		cv.put(FIELD_name, trackName);
		cv.put(FIELD_description, trackDescription);
		return db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + trackID, null) > 0;
	}
	
	public boolean updateTrack(long trackID, int measureVersion) {
		ContentValues cv = new ContentValues();
		cv.put(FIELD_measureVersion, measureVersion);
		if(db == null) open();
		return db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + trackID, null) > 0;
	}
	
	public long insertTrackTid(long trackID, long tid, int tprivacy) {
		long rowid = 0;
		if(db == null) open();
		db.beginTransaction();
		try {
			ContentValues cv = new ContentValues();
			cv.put(FIELD_trackid, trackID);
			cv.put(FIELD_td_tid, tid);
			cv.put(FIELD_privacy, tprivacy);
			rowid = db.insert(TUDING_TABLE, null, cv);
			db.setTransactionSuccessful();
		} catch(Exception e) {
		} finally {
			db.endTransaction();
		}
		return rowid;
	}
	
	public int getTrackTprivacy(long trackID) {
		int tp = 0;
		if(db == null) open();
		try {
			Cursor mCursor = db.query(false, TUDING_TABLE, new String[] {
					FIELD_trackid, 
					FIELD_td_tid,
					FIELD_privacy,
					}, 
					FIELD_trackid + "=" + trackID, 
					null,
					null, 
					null, 
					null, 
					null);
			if (mCursor != null) {
				mCursor.moveToFirst();
				tp = mCursor.getInt(mCursor.getColumnIndexOrThrow(FIELD_privacy));
			}
			mCursor.close();
		} catch(Exception e){
			e.printStackTrace();
		}
		
		return tp;
	}
	
	public boolean updateTrackTprivacy(long trackID, int tprivacy) {
		ContentValues cv = new ContentValues();
		cv.put(FIELD_privacy, tprivacy);
		return db.update(TUDING_TABLE, cv, FIELD_trackid + "=" + trackID, null) > 0;
	}
	
	public long getTrackTid(long trackID) {
		long tid = 0;
		if(db == null) open();
		try {
			Cursor mCursor = db.query(false, TUDING_TABLE, new String[] {
					FIELD_trackid, 
					FIELD_td_tid,
					}, 
					FIELD_trackid + "=" + trackID, 
					null,
					null, 
					null, 
					null, 
					null);
			if (mCursor != null) {
				mCursor.moveToFirst();
				tid = mCursor.getLong(mCursor.getColumnIndexOrThrow(FIELD_td_tid));
			}
			mCursor.close();
		} catch(Exception e){
			e.printStackTrace();
		}
		
		
		return tid;
	}
	
	public boolean updateTrack(long trackID, long totalTime, float totalDistance, 
			float averageSpeed, float maximumSpeed, double minAltitude, double maxAltitude, 
			long trackPoints, int measureVersion, int actionNotesNum, int actionPhotoNum) {
		ContentValues cv = new ContentValues();
		cv.put(FIELD_totalTime, totalTime);
		cv.put(FIELD_totalDistance, totalDistance);
		cv.put(FIELD_averageSpeed, averageSpeed);
		cv.put(FIELD_maximumSpeed, maximumSpeed);
		cv.put(FIELD_minAltitude, minAltitude);
		cv.put(FIELD_maxAltitude, maxAltitude);
		cv.put(FIELD_trackPoints, trackPoints);
		cv.put(FIELD_action_note, actionNotesNum);
		cv.put(FIELD_action_photo, actionPhotoNum);
		//cv.put(FIELD_measureVersion, measureVersion);
		return db.update(TRACKS_TABLE, cv, FIELD_trackid + "=" + trackID, null) > 0;
	}
	

	
	//---retrieves all trackPoints---
	public Cursor getTrackPoints(long rowId) throws SQLException {
		Log.i("TRACK","getTrackPoints id is "+rowId);
		Cursor mCursor = db.query(false, WAYPOINTS_TABLE, new String[] {
						FIELD_trackid, 
						FIELD_time,
						FIELD_latitude,
						FIELD_longitude,
						FIELD_altitude,
						FIELD_speed,
						FIELD_bearing,
						FIELD_accuracy,
						FIELD_actionType,
						FIELD_actionID,
						}, 
						FIELD_trackid + "=" + rowId, 
						null,
						null, 
						null, 
						null, 
						null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}
	
	public static void setGMTTimeString(Location location, String strGMTTime) {
		Bundle bundle = new Bundle();
		bundle.putString(GMTTime, strGMTTime);
		location.setExtras(bundle);
	}
	
	public static String getGMTTimeString(Location location) {
		Bundle bundle = location.getExtras();
		String strGMTTime = bundle.getString(GMTTime);
		return strGMTTime;
	}
	
	public boolean isMeasureUpdated(long trackID) {
		boolean result = true;
		Cursor mCursor = db.rawQuery("select "+FIELD_measureVersion+" from "+TRACKS_TABLE+" where "+FIELD_trackid+"="+trackID, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		int measureVersion = mCursor.getInt(0);
		mCursor.close();
		//Log.i("TRACK","TrackAnalyzer.measureVersion:"+ TrackAnalyzer.measureVersion+" measureVersion"+measureVersion);
		if (TrackAnalyzer.measureVersion < measureVersion) {
			result = false;
		}
		return result;
	}
	
}
